<!-- 过站记录查询 -->
<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :search.sync="search"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @search-change="searchChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot="referenceForm">
        <avue-crud v-show="referenceResult.length > 0" :option="referenceOption" :table-loading="loading" :data="referenceResult"></avue-crud>
      </template>

      <template slot="attachmentsForm">
        <div style="display: flex; width: 100%; height: 200px; overflow: auto" v-html="form.attachments"></div>
      </template>
      <template slot-scope="" slot="createTimeSearch">
        <el-date-picker v-model="search.createTime" type="datetimerange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker>
      </template>
      <template slot="menuLeft">
        <el-button type="warning" size="small" icon="el-icon-download" @click="handleExport">导出</el-button>
      </template>
    </avue-crud>
    <export-comp ref="exportComp" page-api-url="mes-product/transaction/page" :option="option" :page="page" :query="exportParams" file-name="过站记录"> </export-comp>
  </basic-container>
</template>

<script>
import { getList, getDetail } from '@/api/product/missStationRecordQuery';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import exportComp from '@/components/export-comp';
import search from '@/page/index/search';
export default {
  name: 'MissStationRecordQuery',
  components: {
    exportComp,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    var CreateTimeValidate = (rule, value, callback) => {
      if (value && value.length) {
        let transactionStartTime = this.$moment(value[0]).format('YYYY-MM-DD HH:mm:ss');
        let transactionEndTime = this.$moment(value[1]).format('YYYY-MM-DD HH:mm:ss');
        let transactionStartTimeGetTime = new Date(transactionStartTime).getTime();
        let transactionEndTimeGetTime = new Date(transactionEndTime).getTime();
        let monthTime = 24 * 3600 * 1000 * 30;
        if (transactionEndTimeGetTime - transactionStartTimeGetTime > monthTime) {
          callback(new Error('过站时间范围请选择一个月内'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      pageCode: 'MISS_STATION_RECORD_QUERY',
      form: {},
      query: {},
      search: {
        createTime: this.getDefaultTime()
      },
      exportParams: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 483px)',
        calcHeight: 30,
        tip: false,
        searchSpan: 6,
        searchShow: true,
        searchMenuSpan: 24,
        searchMenuPosition: 'right',
        searchLabelWidth: 100,
        labelWidth: 120,
        menu: true,
        menuWidth: 100,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: true,
        viewTitle: '详情',
        viewBtnText: '详情',
        addBtn: false,
        delBtn: false,
        editBtn: false,
        selection: false,
        columnBtn: false,
        dialogClickModal: false,
        column: [
          {
            label: '工单号',
            prop: 'workOrderNo',
            search: true
          },
          {
            label: '产品编码',
            prop: 'productPartNo',
            search: true
          },
          {
            label: '过站工序',
            prop: 'routeName',
            search: true,
            type: 'select',
            filterable: true,
            dicUrl: '/api/mes-product/apaasworkstation/workstation/list',
            props: {
              label: 'name',
              value: 'name'
            }
          },
          {
            label: '工序类型',
            prop: 'transactionType',
            dicData: [
              //可做返回类型的转换
              {
                label: '过站',
                value: 'OVERSTATION'
              },
              {
                label: '报工',
                value: 'TIMESHEET'
              },
              {
                label: '测试',
                value: 'TEST'
              },
              {
                label: '老化',
                value: 'AGING'
              },
              {
                label: '包装',
                value: 'PACKING'
              },
              {
                label: '组装',
                value: 'ASSEMBLY'
              },
              {
                label: '上料',
                value: 'FEEDING'
              }
            ]
          },
          {
            label: '序列号',
            search: true,
            prop: 'productSequenceNumber'
          },
          {
            label: '过站数量',
            prop: 'quantity',
            html: true,
            formatter: (val) => {
              if (val.result === 'PASS') {
                return '<span class="text-green">' + val.passQuantity + '</span>';
              } else {
                let passQuantity = Number(val.passQuantity);
                if (passQuantity > 0) {
                  return '<span class="text-green">' + val.passQuantity + '</span>' + ' | ' + '<span class="text-red">' + val.ngQuantity + '</span>';
                } else {
                  return '<span class="text-red">' + val.ngQuantity + '</span>';
                }
              }
            }
          },
          {
            label: '过站结果',
            prop: 'result',
            span: 12,
            search: true,
            type: 'select',
            dicData: [
              { label: 'PASS', value: 'PASS' },
              { label: 'FAIL', value: 'FAIL' }
            ],
            html: true,
            formatter: (val) => {
              if (val.result === 'PASS') {
                return '<span class="text-green">' + 'PASS' + '</span>';
              } else {
                return '<span class="text-red">' + 'FAIL' + '</span>';
              }
            }
          },
          {
            label: '过站载具',
            prop: 'carrierSn',
            span: 12
          },
          {
            label: '操作人',
            width: 100,
            span: 12,
            prop: 'operatorName',
            search: true
          },
          {
            label: '开始时间',
            prop: 'startScanTime'
          },
          {
            label: '过站时间',
            width: 150,
            span: 12,
            prop: 'createTime',
            searchType: 'datetimerange',
            search: true,
            hide: true,
            searchSpan: 6,
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间',
            searchRules: [
              {
                required: false,
                validator: CreateTimeValidate,
                trigger: 'blur'
              }
            ]
          },
          {
            label: '过站时间',
            prop: 'transactionTime'
          },
          {
            label: '所用时长',
            prop: 'durationSpent',
            formatter: (val) => {
              return val.durationSpent ? val.durationSpent + 's' : '';
            }
          },
          {
            label: '测试结果',
            hide: true,
            span: 24,
            type: 'textarea',
            prop: 'productSn',
            maxRows: 3,
            minRows: 3
          },
          {
            label: '记录项',
            prop: 'reference',
            hide: true,
            span: 24,
            formslot: true
          },
          {
            label: '附件',
            prop: 'attachments',
            hide: true,
            span: 24,
            formslot: true
          }
        ]
      },
      data: [],
      pictureList: [],
      referenceOption: {
        height: '130',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        labelWidth: 100,
        border: true,
        index: false,
        viewBtn: false,
        selection: false,
        dialogClickModal: false,
        menu: false,
        refreshBtn: false,
        columnBtn: false,
        addBtn: false,
        column: []
      },
      referenceResult: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  created() {
    // this.query.createTime = this.search.createTime;
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
      let urlQuery = this.$route.query;
      if (urlQuery && urlQuery.sequenceNumber && urlQuery.workOrderNo && urlQuery.passedDateTime && urlQuery.passedResult) {
        this.search.productSequenceNumber = decodeURIComponent(urlQuery.sequenceNumber);
        this.search.workOrderNo = decodeURIComponent(urlQuery.workOrderNo);
        this.search.result = decodeURIComponent(urlQuery.passedResult);
        let createTime = decodeURIComponent(urlQuery.passedDateTime).split(' ')[0];
        if (createTime) {
          this.search.createTime = [createTime + ' ' + '00:00:00', createTime + ' ' + '23:59:59'];
        }
      }
    });
    window.handleDownload = this.handleDownload;
    window.openPreview = this.openPreview;
  },
  methods: {
    getDefaultTime() {
      let startDate = this.$moment(new Date()).format('YYYY-MM-DD');
      let endDate = this.$moment(new Date()).format('YYYY-MM-DD');
      startDate = startDate + ' ' + '00:00:00';
      endDate = endDate + ' ' + '23:59:59';
      return [startDate, endDate];
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      console.log('searchChange');
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      console.log(1);
      try {
        const fields = Object.keys(this.search).filter((item) => !item.includes('$'));
        // 至少一个搜索条件
        const isHaveValue = fields.some((item) => {
          return this.search[item] && this.search[item].length;
        });
        if (!isHaveValue) {
          this.$message.warning('请输入至少一个搜索条件');
          return;
        }
      } catch (e) {
        console.log(e);
      }
      if (this.search.createTime && this.search.createTime.length > 0) {
        params.transactionStartTime = this.$moment(this.search.createTime[0]).format('YYYY-MM-DD HH:mm:ss');
        params.transactionEndTime = this.$moment(this.search.createTime[1]).format('YYYY-MM-DD HH:mm:ss');
        delete this.query.createTime;
      }
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query))
        .then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          for (const item of this.data) {
            let productSequenceNumber = item['productSequenceNumber'] + ',';
            let preLens = productSequenceNumber.length;
            item['elapsedTimeSecond'] = this.formatSeconds(item['elapsedTimeSecond']);
            if (item['componentSns']) {
              item['componentSns'] = item['componentSns'].replace(/^\,+|\,+$/g, '');
              if (item['componentSns'].includes(productSequenceNumber)) {
                item['componentSns'] = item['componentSns'].substr(preLens);
              } else {
                if (item['componentSns'].includes(item['productSequenceNumber'])) {
                  item['componentSns'] = '';
                }
              }
            }
          }
          this.selectionClear();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    beforeOpen(done, type) {
      if (['view'].includes(type)) {
        let transactionType = [
          {
            label: '过站',
            value: 'OVERSTATION'
          },
          {
            label: '报工',
            value: 'TIMESHEET'
          },
          {
            label: '测试',
            value: 'TEST'
          },
          {
            label: '老化',
            value: 'AGING'
          },
          {
            label: '包装',
            value: 'PACKING'
          },
          {
            label: '组装',
            value: 'ASSEMBLY'
          },
          {
            label: '上料',
            value: 'FEEDING'
          }
        ];
        let find = transactionType.find((type) => type.value == this.form['transactionType']);
        if (find) {
          this.form['transactionType'] = find.label;
        }
        this.referenceOption.column = [];
        this.referenceResult = [];
        if (this.form.reference && this.form.reference != null) {
          let reference = JSON.parse(this.form.reference);
          let referenceResult = {};
          this._forEach(reference, (item) => {
            for (const key in item) {
              this.referenceOption.column.push({
                label: key,
                prop: key
              });
            }
            referenceResult = Object.assign(referenceResult, item);
          });
          this.referenceResult = [referenceResult];
        }
        if (this.form.attachments && this.form.attachments != null) {
          let pictureList = JSON.parse(this.form.attachments);
          let str = '';
          this._forEach(pictureList, (item, index) => {
            str =
              str +
              `<div style="width: 200px;margin: 5px 10px">
              <image src="${item.link}" onclick="openPreview('0', '${item.link}')" style="width: 100px;height:100px"></image>
              <div>${item.attachmentName}</div>
              <button type="button" class="el-button el-button--text el-button--small downLoadFile${index}" onclick="handleDownload('${item.link}')"><i class="el-icon-download"></i><span>下载</span></button>
            </div>`;
          });
          this.form.attachments = str;
        }
      }
      done();
    },
    formatSeconds(value) {
      //  秒
      let second = parseInt(value);
      //  分
      let minute = 0;
      //  小时
      let hour = 0;
      //  天
      //  let day = 0
      //  如果秒数大于60，将秒数转换成整数
      if (second > 60) {
        //  获取分钟，除以60取整数，得到整数分钟
        minute = parseInt(second / 60);
        //  获取秒数，秒数取佘，得到整数秒数
        second = parseInt(second % 60);
        //  如果分钟大于60，将分钟转换成小时
        if (minute > 60) {
          //  获取小时，获取分钟除以60，得到整数小时
          hour = parseInt(minute / 60);
          //  获取小时后取佘的分，获取分钟除以60取佘的分
          minute = parseInt(minute % 60);
        }
      }

      let result = '' + parseInt(second) + '秒';
      if (minute > 0) {
        result = '' + parseInt(minute) + '分' + result;
      }
      if (hour > 0) {
        result = '' + parseInt(hour) + '小时' + result;
      }

      return result;
    },

    handleDownload(link) {
      window.open(`${link}`);
    },
    openPreview(index = 0, link) {
      this.$ImagePreview([{ url: link }], index, {
        closeOnClickModal: false
      });
    },
    handleExport() {
      this.exportParams = this.getExportParam();
      this.$refs.exportComp.visible = true;
    },
    getExportParam() {
      const exportParams = this._cloneDeep(this.search);
      exportParams.transactionStartTime = this.$moment(exportParams.createTime[0]).format('YYYY-MM-DD HH:mm:ss');
      exportParams.transactionEndTime = this.$moment(exportParams.createTime[1]).format('YYYY-MM-DD HH:mm:ss');
      delete exportParams.createTime;
      return exportParams;
    }
  }
};
</script>

<style scoped>
/*::v-deep .el-card .el-card__body .avue-crud__menu {*/
/*  display: none;*/
/*}*/
</style>
